package com.my.servlet;

import com.alibaba.fastjson.JSON;
import com.my.bean.PersonInfo;
import com.my.controal.JDBC;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/ShowMy")
public class ShowMy extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理中文乱码
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        String userID = request.getParameter("userID");

        String sql = String.format("SELECT tb_user.userID, tb_ticket.trainID, tb_ticket.source, tb_ticket.dst, tb_ticket.sourcetime, tb_showmy.countt ,tb_showmy.seatNumber " +
                "FROM tb_ticket, tb_user, tb_showmy " +
                "WHERE tb_ticket.trainID = tb_showmy.trainID AND tb_showmy.userID = tb_user.userID AND tb_user.userID = '%s'", userID);

        try {
            ResultSet res = JDBC.Instance().selectTable(sql);

            ArrayList<PersonInfo> array = new ArrayList<>();

            while (res.next()) {
                PersonInfo pi = new PersonInfo();

                pi.setUserID(res.getString("userID"));
                pi.setCountt(res.getInt("countt"));
                pi.setTrainID(res.getString("trainID"));
                pi.setSource(res.getString("source"));
                pi.setDst(res.getString("dst"));
                pi.setSeatNumber(res.getString("seatNumber"));
                pi.setSourcetime(res.getString("sourcetime"));

                array.add(pi);
            }
            String str = JSON.toJSONString(array);
            response.getWriter().print(str);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
